#---------------------------------------------------------------------------
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
#---------------------------------------------------------------------------
#
# shell_builder.py - Use shell scripts to build targets.
#
from src import action
from src.component import Component
from src import filecache
from src.flags import flags
from src.globals import Define
from src.registry import registry
from src import util

from src.mod.file import FileComponent


# ATLAS config interface
def ShellBuilder(name, **kwargs):
  Define(name, ShellBuilderComponent, **kwargs)


class ShellBuilderComponent(Component):

  def Init(self, script, input, output, **kwargs):
    Component.Init(self, **kwargs)

    self.script = registry.Define(self.ConvertPaths(script)[0], FileComponent)
    self.AddDepend(self.script)

    self.input = []
    for i in self.ConvertPaths(input):
      comp = registry.Define(i, FileComponent)
      self.input.append(comp)
      self.AddDepend(comp)

    for t in self.ConvertPaths(output, build_path=True):
      self.AddTarget(registry.Define(util.BuildPath(t), FileComponent))

  def ShowBuildOutputOnSuccess(self):
    # Scripts normally generate lots of output.
    return flags.verbose

  def Build(self):
    util.SetExecutePermission(self.script.GetPath())
    cmd = action.BuildCommand(self.script.GetPath(), 'shell script %s' % self.GetName())
    return cmd.Run()
